package com.qingzhuge.web.interceptor;

import com.qingzhuge.autoconfigure.QingTingProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author : zero.xiao
 * @description : 拦截器基类
 * @modified :
 */
public class Interceptor extends HandlerInterceptorAdapter {
    protected Logger logger = LoggerFactory.getLogger(getClass());
    private Interceptor[] nextInterceptor;

    @Autowired
    protected QingTingProperties qingTingProperties;

    public void setNextInterceptor(Interceptor... nextInterceptor) {
        this.nextInterceptor = nextInterceptor;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (nextInterceptor == null) {
            return true;
        }
        for (Interceptor aNextInterceptor : nextInterceptor) {
            if (!aNextInterceptor.preHandle(request, response, handler)) {
                return false;
            }
        }
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) {
        if (nextInterceptor != null) {
            for (Interceptor aNextInterceptor : nextInterceptor) {
                aNextInterceptor.postHandle(request, response, handler, modelAndView);
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        if (nextInterceptor != null) {
            for (Interceptor aNextInterceptor : nextInterceptor) {
                aNextInterceptor.afterCompletion(request, response, handler, ex);
            }
        }
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (nextInterceptor != null) {
            for (Interceptor aNextInterceptor : nextInterceptor) {
                aNextInterceptor.afterConcurrentHandlingStarted(request, response, handler);
            }
        }
    }
}
